import { wxRequest } from '../../utils/server.js';
const _wxRequest = new wxRequest();
const app = getApp()
Page({ 
  data: {
    imgUrl: app.globalData.imgUrl,
    address: [],
    cententDetail: {
      defaulted:true
    },
    flageTpe:'' 
  },
 
  onLoad: function (options) {
    //订单页进来
    if (options && options.type) {
      this.setData({
        flageTpe: options.type
      })
    }

    var item = wx.getStorageSync('addressItem')
    if (item) {
      this.setData({
        cententDetail: item
      })
    }

  },

  onUnload: function () {
    wx.removeStorageSync('addressItem')
  },

  onHide: function () {
    wx.removeStorageSync('addressItem')
  },


  addressDetail: function (e) {
    this.setData({
      address: e.detail
    })
  },

  formSubmit: function (e) {
    var formdata = e.detail.value;
    formdata.defaulted = formdata.defaulted?1:0;
    var address = this.data.address
    if (address.length > 0) {
      formdata.prov = address[0].name
      formdata.proId = address[0].code
      formdata.city = address[1].name
      formdata.cityId = address[1].code
      formdata.disName = address[2].name
      formdata.disId = address[2].code
    }

    console.log(formdata,'formdata')

    if (formdata.name == '') {
      wx.showToast({
        icon: 'none',
        title: '名称不能为空',
      })
      return
    }

    if (formdata.mobile == '') {
      wx.showToast({
        icon: 'none',
        title: '手机号码不能为空',
      })
      return
    }

    if (formdata.mobile.length != 11) {
      wx.showToast({
        icon: 'none',
        title: '手机号码格式不正确',
      })
      return
    }

    if (formdata.disId == '' || formdata.disName == '') {
      wx.showToast({
        icon: 'none',
        title: '请选择所在地区',
      })
      return
    }

    if (formdata.detailAddress == '') {
      wx.showToast({
        icon: 'none',
        title: '详细地址不能为空',
      })
      return
    }
    
 
    var url = "/odr/protected/customerAddress/save";
    var title = "发布成功"
    //修改
    if (this.data.cententDetail && this.data.cententDetail.id) { 
      formdata.id = this.data.cententDetail.id;
      title = "修改成功"
    }


    //请求
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + url,
      method: 'POST',
      data: formdata
    }, (res) => {  
      //订单页面进去直接跳转到订单页，其他跳转到列表页面
      if (this.data.flageTpe && this.data.flageTpe!="undefined"){ 
        console.log('进')
          var pages = getCurrentPages();
          var prevPage = pages[pages.length - 3]; //上2个页面    
          prevPage.setData({
            defaultAddress: res.vo,
          })

          wx.showToast({
            title,
        })

        setTimeout(() => {
          wx.navigateBack({
            delta:2
          }); 
        }, 1500) 

       }else{ 
        wx.showToast({
          title,
        })
        setTimeout(() => {
          wx.navigateBack(); 
        }, 1500) 

       }

        
    })





  },
})